<template>
    <div class="login">
        <section>
            <div class="loginbox">
                <el-form :model="userobj" label-width="auto" ref="ruleFormRef" :rules="rules">
                    <el-form-item prop="username">
                        <el-input v-model="userobj.username" :prefix-icon="UserFilled" placeholder="请输入用户名"/>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="userobj.password" :prefix-icon="UserFilled" placeholder="请输入密码"/>
                    </el-form-item>
                    <el-form-item class="bnt">
                        <el-button type="primary" @click="onSubmit(ruleFormRef)">登录</el-button>
                        <el-button>重置</el-button>
                    </el-form-item>
                </el-form> 
            </div>
        </section>
    </div>
</template>
<script setup lang="ts">
import {ref,reactive} from "vue"
import {usertype} from "@/utils/type/user.d.ts"
import { UserFilled } from '@element-plus/icons-vue'
import {login} from "@/utils/api/user.ts"
import {userStore} from "@/stores/user.ts"
import {useRouter} from "vue-router"
const router=useRouter()

const store=userStore()

const userobj=ref<usertype>({
    username:"",
    password:""
})

//定义表单实例
const ruleFormRef = ref()

//定义验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 6', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 6, message: 'Length should be 3 to 6', trigger: 'blur' },
    ]
  })

//提交
const onSubmit=()=>{
    //走验证
    ruleFormRef.value.validate(async(flag)=>{
        if(!flag){
            return false
        }
        //走接口
        let {data:res}=await login(userobj.value)
        if(res.meta.status==200){
            //成功
            store.setuser(res.data)
            router.push("/")
            ElMessage.success(res.meta.msg)
        }else{
            //不成功
            ElMessage.error(res.meta.msg)
        }
    })
    
}
</script>
<style lang="scss">
.login{
    background: #2b4b6b;
    display: flex;
    justify-content: center;
    align-items: center;
    &>section{
        width:450px;
        height:304px;
        background: #fff; 
    }
    .loginbox{
        padding:150px 20px 20px 20px;
        
    }

    .bnt .el-form-item__content{
        display: flex;
        justify-content: flex-end;
    }
}
</style>